package com.leenmvc.core.security.service.core;

import com.leenmvc.core.annotation.TransactionMulti;
import com.leenmvc.core.base.BaseService;
import com.leenmvc.core.dao.communal.Wrapper;
import com.leenmvc.core.dao.mysql.wrapper.QueryWrapper;
import com.leenmvc.core.exception.BusinessException;
import com.leenmvc.core.security.dao.core.SysLanguageDao;
import com.leenmvc.core.security.entity.core.SysLanguage;
import com.leenmvc.core.security.entity.core.SysMenu;
import com.leenmvc.core.security.entity.core.SysMenuPermisson;
import com.leenmvc.core.utils.TipUtil;
import com.leenmvc.core.utils.http.HttpContextUtils;
import com.leenmvc.core.utils.validator.ValidatorUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysMenuService extends BaseService<SysMenu> {

    private final static Logger logger = LoggerFactory.getLogger(SysMenuService.class);

    @Autowired
    private SysLanguageDao sysLanguageDao;

    @Autowired
    private SysLanguageService sysLanguageService;

    @Autowired
    private SysMenuPermissonService sysMenuPermissonService;

    /**
     * 添加一个菜单到工程中
     *
     * @param t
     */
    @TransactionMulti
    public <T> boolean insert(T t) {
        SysMenu sysMenu = (SysMenu) t;
        if (!super.insert(sysMenu)) {
            throw new BusinessException("INSERT_FAIL", SysMenu.class);
        }
        // 新增菜单与权限关系
        List<SysMenuPermisson> menuPermissionList = sysMenu.getMenuPermissionList();
        if (menuPermissionList.size() > 0){
            menuPermissionList.forEach(sysMenuPermisson->{
                sysMenuPermisson.setMenuId(sysMenu.getId());
                sysMenuPermissonService.insert(sysMenuPermisson);
            });
        }

        // 语言表新增一条记录
        SysLanguage language = new SysLanguage();
        language.setTableName("sys_menu");
        language.setTableId(sysMenu.getId());
        language.setLanguage("zh-CN");
        language.setFieldName("name");
        language.setFieldValue(sysMenu.getName());
        if (!sysLanguageDao.insert(language)) {
            throw new BusinessException("INSERT_FAIL", SysLanguage.class);
        }
        return true;
    }

    /**
     * 更新一个菜单到工程中
     *
     * @param t
     */
    @TransactionMulti
    public <T> boolean update(T t) {
        SysMenu sysMenu = (SysMenu) t;
        // 修改菜单与权限关系

        // 先删除菜单与权限关系
        sysMenuPermissonService.delete("menuId",sysMenu.getId());
        // 在新增权限菜单关系
        List<SysMenuPermisson> menuPermissionList = sysMenu.getMenuPermissionList();
        if (menuPermissionList.size()>0){
            menuPermissionList.forEach(sysMenuPermisson->{
                sysMenuPermissonService.insert(sysMenuPermisson);
            });
        }
        Wrapper eq = getUpdateWrapper(SysLanguage.class);
                eq.addSet("fieldValue", sysMenu.getName())
                .eq("tableId", sysMenu.getId())
                .eq("language", HttpContextUtils.getLanguage())
                .eq("tableName", "sys_menu");

        if (sysLanguageDao.updateByWrapper(eq) <= 0) {
            throw new BusinessException("UPDATE_FAIL", SysLanguage.class);
        }

        if (!super.update(sysMenu)) {
            throw new BusinessException("UPDATE_FAIL", SysMenu.class);
        }
        return true;
    }

    /**
     * 从工程中删除菜单
     *
     * @param ids
     */
    @TransactionMulti
    public int deleteByIds(Object[] ids) {
        int count = 0;
        for (Object id : ids) {
            int childCount = count("pid", id);
            if (childCount > 0) {
                throw new BusinessException(TipUtil.getTip("SYSMENU_DELETEBYIDS_HAVE_CHILDS"));
            }
            if (!deleteById(id)) {
                logger.info("删除菜单的是否发生错误！！id为：{}", id);
            } else {
                ++count;
            }

            // 删除菜单对应权限关系
            sysMenuPermissonService.delete("menuId",id);
        }
        return count;
    }


    @Override
    public <T> T get(Object id) {
        SysMenu menu = super.get(id);
        ValidatorUtils.notNull(TipUtil.getTip("NOT_NULL"), menu);
        Wrapper queryWrapper = getQueryWrapper(SysLanguage.class);
        queryWrapper.incField("fieldValue");
        queryWrapper.eq("tableId", id);
        queryWrapper.eq("language", HttpContextUtils.getLanguage());
        queryWrapper.eq("tableName", "sys_menu");
        menu.setName(sysLanguageService.getOneField(queryWrapper));

        QueryWrapper eq = getQueryWrapper(SysLanguage.class);
        eq.incField("fieldValue")
                .eq("tableId", menu.getPid())
                .eq("language", HttpContextUtils.getLanguage())
                .eq("tableName", "sys_menu");
        menu.setParentName(sysLanguageService.getOneField(eq));
        // 获取菜单与权限的关系
        List<SysMenuPermisson> menuPermissonList = sysMenuPermissonService.getList("menuId", id);
        menu.setMenuPermissionList(menuPermissonList);
        return (T) menu;
    }

    /**
     * 通过角色id获取对应的
     * @param roleId
     * @return
     */
    public List<SysMenu> getMenuListForRole(Long roleId) {
        List<SysMenu> menulist = listBySqlKey("getMenuListForRole", "language", HttpContextUtils.getLanguage(),"roleId",roleId);
        return menulist;
    }



}
